package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    //@RequiresPermissions("permission:list")
    //@RequriedPermission(name="权限列表",expression="permission:list")
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model) {
        PageInfo pageInfo = this.permissionService.query(qo);
        model.addAttribute("result", pageInfo);
        return "permission/list";
    }

    //@RequiresPermissions("permission:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            this.permissionService.delete(id);
            return new JsonResult("操作成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("操作失败", false);
        }
    }

    //对load（）请求进行异常处理
    @RequestMapping("/load")
    public JsonResult load() {
        JsonResult json = new JsonResult();
        try {
            this.permissionService.load();
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            json.mark("操作失败");
        }
        return json;
    }
    /*@RequestMapping({"/input"})
    public String input(Long id, Model model)
    {
        if (id != null) {
            model.addAttribute("entity", this.permissionService.get(id));
        }
        return "permission/input";
    }*/

    //@RequiresPermissions("permission:saveOrUpdate")
    @RequestMapping({"/saveOrUpdate"})
    @ResponseBody
    public JsonResult saveOrUpdate(Permission entity) {
        try {
            if (entity.getId() == null) {
                this.permissionService.saveOrUpdate(entity);
            } else {
                this.permissionService.saveOrUpdate(entity);
            }
            return new JsonResult("操作成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("操作失败", false);
        }
    }


}
